<!--  -->
<template>
  <div class="singer">
    <div class="singer-content">
      <div class="listview"
            ref="singer"
            @scroll="scrollList">
        <ul v-show="singerList.length">
          <li class="list-group"
              v-for="(item, index) of singerList"
              :key="index"
              ref="listgount">
            <h2 class="list-group-title">{{item.title}}</h2>
            <uL>
              <li class="list-group-item"
                  v-for="(itemList, indexs) of item.items"
                  :key="indexs">
                <img class="avatar" v-lazy="itemList.singURL">
                <span class="name">{{itemList.name}}</span>
              </li>
            </uL>
          </li>
        </ul>
        <div class="list-shortcut"
              @touchstart.stop.prevent="onShortcutTouchStart" @touchmove.stop.prevent="onShortcutTouchMove">
          <ul>
            <li class="item"
                v-for="(item, index) of shortList"
                :key="index"
                :class="{'current':currentIndex===index}"
                :data-index="index">{{item}}</li>
          </ul>
        </div>
        <!-- <div class="list-fixed">
          <div class="fixed-title"></div>
        </div> -->
      </div>
    </div>
  </div>
</template>

<script>
import { getSingerList, ERR_OK } from '@/api/recommend'
import Bscroll from 'better-scroll'
import Singer from '@/common/js/singer'

const hotName = '热门'
const hotSingerLen = 10
const anchorHeight = 18
const titleHeight = 30

export default {
  name: 'Singer',
  data () {
    return {
      singerList: Array,
      shortList: Array,
      scrollY: -1,
      currentIndex: 0,
      listenScroll: true,
      listHeight: []
    }
  },
  mounted () {
    setTimeout(() => {
      if (!this.scroll) {
        this.scroll = new Bscroll(this.$refs.singer, {
          probeType: 3,
          scrollX: false,
          scrollY: true,
          mouseWheel: true,
          click: true,
          taps: true
        })
      } else {
        this.scroll.refresh()
      }
      if (this.scroll) {
        this.scroll.on('scroll', (pos) => {
          this.scrollList(pos)
          this._calculateHeight()
        })
      }
    }, 20)
  },
  created () {
    this._getSingerList()
    this.touch = {}
  },
  methods: {
    // 得到歌手列表
    _getSingerList () {
      getSingerList().then((res) => {
        if (res.code === ERR_OK) {
          this.singerList = res.data.list
          this.singerList = this._initSinger(this.singerList)
          this.shortList = this._shortList(this.singerList)
        }
      })
    },
    // 遍历数组-并对数组进行排序
    _initSinger (list) {
      let mapList = {
        hot: {
          title: hotName,
          items: []
        }
      }
      // 遍历歌手列表数据
      list.forEach((item, index) => {
        // 数组获取热门推荐数据
        if (index < hotSingerLen) {
          mapList.hot.items.push(new Singer({
            id: item.Fsinger_mid,
            name: item.Fsinger_name
          }))
        }
        // 获取其他的列表的数据
        let key = item.Findex
        if (!mapList[key]) {
          mapList[key] = {
            title: key,
            items: []
          }
        }
        mapList[key].items.push(new Singer({
          id: item.Fsinger_mid,
          name: item.Fsinger_name
        }))
      })
      // 为了得到有序列表，我们需要处理 mapList
      let ret = []
      let hot = []
      for (let key in mapList) {
        let val = mapList[key]
        if (val.title.match(/[a-zA-Z]/)) {
          ret.push(val)
        } else if (val.title === hotName) {
          hot.push(val)
        }
      }
      ret.sort((a, b) => {
        return a.title.charCodeAt(0) - b.title.charCodeAt(0)
      })
      return hot.concat(ret)
    },
    // 显示右侧滑动列表
    _shortList (hotList) {
      return hotList.map((shortCode) => {
        return shortCode.title.substr(0, 1)
      })
    },
    // 点击右侧列表左侧滚动
    onShortcutTouchStart (e) {
      let anchorIndex = this.getData(e.target, 'index')
      let firstTouch = e.touches[0]
      this.touch.y1 = firstTouch.pageY
      this.touch.anchorIndex = anchorIndex
      this.scroll.scrollToElement(this.$refs.listgount[anchorIndex], 0)
    },
    onShortcutTouchMove (e) {
      let firstTouch = e.touches[0]
      this.touch.y2 = firstTouch.pageY
      let delta = (this.touch.y2 - this.touch.y1) / anchorHeight | 0
      let anchorIndex = parseInt(this.touch.anchorIndex) + delta
      this.scroll.scrollToElement(this.$refs.listgount[anchorIndex], 0)
    },
    getData (el, name, val) {
      const prefix = 'data-'
      if (val) {
        return el.setAttribute(prefix + name, val)
      } else {
        return el.getAttribute(prefix + name)
      }
    },
    // 滚动显示
    scrollList (pos) {
      this.scrollY = pos.y
    },
    _calculateHeight () {
      this.listHeight = []
      const list = this.$refs.listgount
      let height = 0
      this.listHeight.push(height)
      for (let i = 0; i < list.length; i++) {
        let item = list[i]
        height += item.clientHeight - 30
        this.listHeight.push(height)
      }
    }
  },
  watch: {
    data () {
      setTimeout(() => {
        this._calculateHeight()
      }, 20)
    },
    scrollY (newY) {
      const listHeight = this.listHeight
      // console.log(listHeight)
      // 当滚动到顶部，newY>0
      if (newY > 0) {
        this.currentIndex = 0
        return
      }
      // 在中间部分滚动
      for (let i = 0; i < listHeight.length - 1; i++) {
        let height1 = listHeight[i]
        let height2 = listHeight[i + 1]
        if (-newY >= height1 && -newY < height2) {
          this.currentIndex = i
          this.diff = height2 + newY
          console.log(this.currentIndex)
          return
        }
      }
      // 当滚动到底部，且-newY大于最后一个元素的上限
      this.currentIndex = listHeight.length - 2
    },
    diff (newVal) {
      let fixedTop = (newVal > 0 && newVal < titleHeight) ? newVal - titleHeight : 0
      if (this.fixedTop === fixedTop) {
        return
      }
      this.fixedTop = fixedTop
      this.$refs.fixed.style.transform = `translate3d(0,${fixedTop}px,0)`
    }
  }
}
</script>

<style lang='stylus' scoped>
  @import "~@/common/stylus/variable"
  .singer
    position: fixed
    top: 88px
    bottom: 0
    width: 100%
    .singer-content
      height 100%
      overflow hidden
      .listview
        position: relative
        width: 100%
        height: 100%
        overflow: hidden
        background: $color-background
        .list-group
          padding-bottom: 30px
          .list-group-title
            height: 30px
            line-height: 30px
            padding-left: 20px
            font-size: $font-size-small
            color: $color-text-l
            background: $color-highlight-background
          .list-group-item
            display: flex
            align-items: center
            padding: 20px 0 0 30px
            .avatar
              width: 50px
              height: 50px
              border-radius: 50%
            .name
              margin-left: 20px
              color: $color-text-l
              font-size: $font-size-medium
        .list-shortcut
          position: absolute
          z-index: 30
          right: 0
          top: 50%
          transform: translateY(-50%)
          width: 20px
          padding: 20px 0
          border-radius: 10px
          text-align: center
          background: $color-background-d
          font-family: Helvetica
          .item
            padding: 3px
            line-height: 1
            color: $color-text-l
            font-size: $font-size-small
            &.current
              color: $color-theme
        .list-fixed
          position: absolute
          top: 0
          left: 0
          width: 100%
          .fixed-title
            height: 30px
            line-height: 30px
            padding-left: 20px
            font-size: $font-size-small
            color: $color-text-l
            background: $color-highlight-background
        .loading-container
          position: absolute
          width: 100%
          top: 50%
          transform: translateY(-50%)
</style>
